// ./config-overrides.js
/**
 * React App Rewired configuration
 * Adds support for server function comment markers
 */
const path = require('path');

console.log('🔧 CONFIG-OVERRIDES: Loading config-overrides.js file');
console.log('🔧 CONFIG-OVERRIDES: Current working directory:', process.cwd());
console.log('🔧 CONFIG-OVERRIDES: __dirname:', __dirname);

module.exports = function override(config, env) {
  console.log('🔧 CONFIG-OVERRIDES: Override function called!');
  console.log('🔧 CONFIG-OVERRIDES: Environment:', env);
  console.log('🔧 CONFIG-OVERRIDES: Config type:', typeof config);
  console.log('🔧 CONFIG-OVERRIDES: Existing rules count:', config.module?.rules?.length || 0);
  
  const loaderPath = path.resolve(__dirname, './server-marker-loader.js');
  console.log('🔧 CONFIG-OVERRIDES: Loader path:', loaderPath);
  
  // Check if loader file exists
  const fs = require('fs');
  const loaderExists = fs.existsSync(loaderPath);
  console.log('🔧 CONFIG-OVERRIDES: Loader file exists:', loaderExists);
  
  // Add the server marker loader
  const newRule = {
    test: /\.(js|jsx|ts|tsx)$/,
    exclude: /node_modules/,
    use: [
      {
        loader: loaderPath,
      }
    ]
  };
  
  console.log('🔧 CONFIG-OVERRIDES: Adding new webpack rule:', JSON.stringify(newRule, null, 2));
  
  config.module.rules.push(newRule);
  
  console.log('🔧 CONFIG-OVERRIDES: New rules count:', config.module.rules.length);

  // Add Node.js polyfills for client-side
  config.resolve = config.resolve || {};
  config.resolve.fallback = {
    ...config.resolve.fallback,
    "fs": false,
    "os": false,
    "path": false,
    "vm": false
  };
  
  console.log('🔧 CONFIG-OVERRIDES: Added Node.js polyfills');
  console.log('🔧 CONFIG-OVERRIDES: Final config rules count:', config.module.rules.length);
  console.log('🔧 CONFIG-OVERRIDES: Override function complete!');

  return config;
};